package com.example.day_day_up.listener;

import com.example.day_day_up.mappers.*;
import com.example.day_day_up.service.*;
import com.example.day_day_up.service.impl.*;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.IOException;
import java.io.InputStream;

@WebListener
public class MyWebAppContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        try (InputStream is = Resources.getResourceAsStream("mybatis.xml")) {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            ServletContext servletContext = sce.getServletContext();

            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            servletContext.setAttribute("sqlSession", sqlSession);

            // 创建mapper
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            CourseMapper courseMapper = sqlSession.getMapper(CourseMapper.class);
            MaterialMapper materialMapper = sqlSession.getMapper(MaterialMapper.class);
            MaterialStatusMapper materialStatusMapper = sqlSession.getMapper(MaterialStatusMapper.class);
            ExamMapper examMapper = sqlSession.getMapper(ExamMapper.class);
            ExamStatusMapper examStatusMapper = sqlSession.getMapper(ExamStatusMapper.class);
            CommentMapper commentMapper = sqlSession.getMapper(CommentMapper.class);

            // 存储mapper ?

            // 创建service
            UserService userService = new UserServiceImpl(userMapper);
            CourseService courseService = new CourseServiceImpl(courseMapper);
            MaterialService materialService = new MaterialServiceImpl(materialMapper, materialStatusMapper);
            ExamService examService = new ExamServiceImpl(examMapper, examStatusMapper);
            CommentService commentService = new CommentServiceImpl(commentMapper);

            // 存储service
            servletContext.setAttribute("userService", userService);
            servletContext.setAttribute("courseService", courseService);
            servletContext.setAttribute("materialService", materialService);
            servletContext.setAttribute("examService", examService);
            servletContext.setAttribute("commentService", commentService);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        SqlSession sqlSession = (SqlSession) servletContext.getAttribute("sqlSession");
        sqlSession.close();
    }
}
